package com.novunda.platform.web;

import com.novunda.platform.common.utils.MailUtil;
import com.novunda.platform.common.utils.StringUtil;
import com.novunda.platform.common.web.controller.BaseController;
import com.novunda.platform.common.web.modal.Page;
import com.novunda.platform.entities.EmailInfo;
import com.novunda.platform.entities.User;
import com.novunda.platform.services.EmailService;
import com.novunda.platform.services.UserService;
import com.novunda.tca.tdk.TCAClient;
import com.novunda.tca.tdk.utils.BusinessTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 注册管理
 * Created by YJY on 2016/9/9.
 */
@Controller
@RequestMapping("/registerManage")
public class RegisterManageController extends BaseController {

    /**
     * 用户服务
     */
    @Autowired
    private UserService userService;

    /**
     * 邮件服务器查询
     */
    @Autowired
    private EmailService emailService;

    @Autowired
    private Environment env;

    String tip;

    Map<String, Object> tipMap = new HashMap<>();
    /**
     * 机构下的注册信息
     *
     * @param request      请求
     * @param response     响应
     * @param model        存放信息，request级别的
     * @param queryKeyWord 查询关键字
     * @param organization 机构
     * @return 跳转地址
     */
    @RequestMapping("/registerInfo")
    @RequiresPermissions("sys:register:view")
    public String registerInfo(HttpServletRequest request, HttpServletResponse response, Model model, String queryKeyWord, String organization) {
        return risList(request, response, model, queryKeyWord, organization);
    }

    /**
     * 机构下的注册信息
     *
     * @param request      请求
     * @param response     响应
     * @param model        存放信息，request级别的
     * @param queryKeyWord 查询关键字
     * @param organization 机构
     * @return 跳转地址
     */
    private String risList(HttpServletRequest request, HttpServletResponse response, Model model, String queryKeyWord, String organization) {
        String keyWord = "";
        if ("请输入搜索条件...".equals(queryKeyWord)) {
            keyWord = "";
        }
        if(!StringUtil.isEmpty(queryKeyWord)){
            keyWord = queryKeyWord.trim();
        }
        Page<User> page = userService.findUserByPaging(new Page<User>(request, response), keyWord, organization);
        model.addAttribute("page", page);
        //激活用户
        int activateUser = userService.queryActivateUser(organization, keyWord);
        //未激活账号数
        int notActivateUser = userService.queryNotActivateUser(organization, keyWord);
        model.addAttribute("activateUser", activateUser);
        model.addAttribute("notActivateUser", notActivateUser);
        model.addAttribute("userCount", page.getCount());
        model.addAttribute("queryKeyWord", keyWord);
        model.addAttribute("organization", organization);
        return "modules/conf/register";
    }

    /**
     * 发送邮件
     *
     * @param emails 邮件地址
     * @return 跳转地址
     */
    @ResponseBody
    @RequestMapping(value = "/sendEmail", produces = "application/json; charset=UTF-8")
    @RequiresPermissions("sys:register:edit")
    public Map<String, Object> sendEmial(Long[] ids, Model model, String queryKeyWord, String organization, HttpServletRequest request, HttpServletResponse response) {

        tipMap.put("message", "");
        tipMap.put("ids", "");
        tipMap.put("code", "1");
        //判断用户集合是否;为空
        if (ids == null) {
            tipMap.put("message", "请先选择收件人信息");
            tip = "请先选择收件人信息";
//            addMessage(model, "请先选择收件人信息！");
//            return risList(request, response, model, queryKeyWord, organization);
            return tipMap;
        }
        List<Long> data = new ArrayList<>();
        Collections.addAll(data, ids);
        for (int i = 0; i < data.size(); i++) {
            User user = userService.getUser(data.get(i));
            if (user == null) {
                tipMap.put("message", "该用户不存在");
                tip = "该用户不存在！";
//                addMessage(model, "该用户不存在！");
//                return risList(request, response, model, queryKeyWord, organization);
                return tipMap;
            }
            //邮件服务器信息
            List<EmailInfo> emailInfos = emailService.queryEmailInfo(user.getCompany().getName());
            //判断邮件服务器是否为空
            if (emailInfos != null && !emailInfos.isEmpty()) {
                //不为空
                if (emailsNotNull(data, model, i, emailInfos)) {
                    return tipMap;
//                    return risList(request, response, model, queryKeyWord, organization);
                }
            } else {
                //为空
                if (!sendEmailResult(null, user.getEmail(), data, i, model)) {
                    return tipMap;
//                    return risList(request, response, model, queryKeyWord, organization);
                }
            }
        }
        tipMap.put("message", "邮件发送成功");
        tipMap.put("code", "0");
        addMessage(model, "邮件发送成功！");
        return tipMap;
//        return risList(request, response, model, queryKeyWord, organization);
    }

    @RequestMapping("/rs")
    public String registerSikp(String token, HttpServletRequest request) {
        User user = userService.findUserByToken(token);
        if (user == null || user.getState() == 2) {
            return "errors/warning";
        } else {
            if (System.currentTimeMillis() - user.getEmailSendTime() > Long.valueOf(env.getProperty("broken_time"))) {
                return "errors/warning";
            } else {
                String qrUrl = new TCAClient().getTcaAddress(BusinessTypeEnum.DEVICE_BIND,env.getProperty("granted_auth"), env.getProperty("local_auth"), user.getLoginName() + ":::", "绑定");
                return "redirect:" + qrUrl;
            }
        }
    }

    /**
     * 邮件服务器不为空的情况
     *
     * @param users      用户列表
     * @param model      存放信息，request级别的
     * @param i          列表索引
     * @param emailInfos 邮件服务器信息
     * @return 是否发送成功 true 发送失败
     */
    private boolean emailsNotNull(List<Long> ids, Model model, int i, List<EmailInfo> emailInfos) {
        //判断该机构下是否只有一个邮件服务器
        if (emailInfos.size() == 1) {
            //只有一个邮件服务器的情况
            return !sendEmailResult(emailInfos.get(0), userService.getUser(ids.get(i)).getEmail(), ids, i, model);
        } else {
            //多个邮件服务器的情况
            return manyEmailServer(ids, model, i, emailInfos);
        }
    }

    /**
     * 多个邮件服务器情况
     *
     * @param users      用户列表
     * @param model      存放信息，request级别的
     * @param i          列表索引
     * @param emailInfos 邮件服务器信息
     * @return 是否发送成功 true 发送失败
     */
    private boolean manyEmailServer(List<Long> ids, Model model, int i, List<EmailInfo> emailInfos) {
        //记录是否有默认邮件服务器
        boolean temp = false;
        //遍历邮件服务器
        for (EmailInfo emailInfo : emailInfos) {
            //判断是否是默认服务器
            if (emailInfo.isDefaultEmail()) {
                //判断发送结果
                if (!sendEmailResult(emailInfo, userService.getUser(ids.get(i)).getEmail(), ids, i, model)) {
                    return true;
                }
                temp = true;
                break;
            }
        }
        //没有邮件服务器的情况
        if (!temp) {
            //判断发送结果
            if (!sendEmailResult(emailInfos.get(0), userService.getUser(ids.get(i)).getEmail(), ids, i, model)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 发送邮件
     *
     * @param send          邮件服务器
     * @param receiverEmail 接收邮件地址
     * @param users         用户列表
     * @param i             列表索引
     * @param model         存放信息，request级别的
     * @return 发送结果 true成功
     */
    private boolean sendEmailResult(EmailInfo send, String receiverEmail, List<Long> ids, int i, Model model) {
        if (send == null) {
            return returnResult(ids, i, model);
        }
        UUID uuid = UUID.randomUUID();
        User user = userService.getUser(ids.get(i));
        user.setEmailSendTime(System.currentTimeMillis());
        user.setUuid(uuid.toString());
        String url = env.getProperty("register_address") + "?token=" + uuid.toString();
        send.setEmailContent(send.getEmailContent() + "<br/><div><a href='" + url + "'>" + url + "</a></div>");
        userService.saveUser(user);
        //判断是否是没有邮件服务器或者发送失败
        if (!new MailUtil().send(send, receiverEmail)) {
            return returnResult(ids, i, model);
        }
        return true;
    }

    /**
     * 去除发送失败机构下的所有用户
     *
     * @param users 用户列表
     * @param i     列表索引
     * @param model 存放信息，request级别的
     * @return 固定返回false, 表示邮件发送失败
     */
    private boolean returnResult(List<Long> ids, int i, Model model) {
        List<Long> userList = ids.subList(i + 1, ids.size());
        List<User> idList = new ArrayList<>();
        //把剩余的邮件信息添加到idList
        for (Long anUserList : userList) {
            idList.add(userService.getUser(anUserList));
        }
        List<Long> returnUsers = new ArrayList<>();
        Long companyId = userService.getUser(ids.get(i)).getCompany().getId();
        //遍历idList
        for (User user : idList) {
            //剔除已经发送失败的机构
            if (!user.getCompany().getId().equals(companyId)) {
                returnUsers.add(user.getId());
            }
        }
        //判断returnUsers是否为空，给出相应的提示
        if (returnUsers.isEmpty()) {
            tip = userService.getUser(ids.get(i)).getCompany().getName() + ",邮件发送失败！";
            tipMap.put("message", tip);
            addMessage(model, userService.getUser(ids.get(i)).getCompany().getName() + ",邮件发送失败！");
        } else {
            tip = userService.getUser(ids.get(i)).getCompany().getName() + ",邮件发送失败！是否继续发送其它邮件？";
            tipMap.put("message", tip);
            tipMap.put("ids", returnUsers);
            addRisMessage(model, userService.getUser(ids.get(i)).getCompany().getName() + ",邮件发送失败！是否继续发送其它邮件？");
            model.addAttribute("ids", returnUsers);
        }
        return false;
    }
}
